<template>
    <div>
        <i-table border stripe  :columns="format" :data="show_list" height="760">
            <template slot-scope="{ row, index }" slot="action">
                <Button type="primary" style="margin-bottom: 5px "  v-if="show_list[index].status!=99" @click="btn_edit_release(index)">编辑</Button>
            </template>
        </i-table >
        <div style="text-align: center;margin-top: 10px;">
            <Page ref="page" :total="total" :page-size="pageSize"  @on-change="changePage" show-total/>
        </div>

        <Modal v-model="show_edit_bg_modal" draggable width="800" :closable="false">
            <p slot="header" style="color:#f60;text-align:center;height:30px">
               <Row>
                   <i-col span="2"><span>编辑发布</span></i-col>
                   <i-col span="2" offset="20"><Button type="primary" v-if="[2,11,12,13].includes(release_edit.status)"  @click="btn_bg_release_offline">下线</Button></i-col>
               </Row>
            </p>
            <strong>版本信息</strong>
            <Row>
                <i-col span="9" offset="3">
                    新版： 
                    <Button type="primary" v-if="[3,11].includes(release_edit.status) "  @click="btn_change_weight('new')">接管流量</Button>
                </i-col>
                <i-col span="9" offset="3">
                    旧版：
                    <Button  type="primary"  v-if="[2,12,13].includes(release_edit.status)" @click="btn_change_weight('old')">接管流量</Button>
                </i-col>
            </Row>
            <div slot="footer" class="modal_footer">
                <Button type="primary"  @click="btn_close_bg_modal">关闭</Button>
            </div>
        </Modal>
        
        <!-- 编辑灰度发布 -->
        <Modal v-model="show_edit_gray_modal"  width="900" :closable="false"  >
            <p slot="header" style="color:#f60;text-align:center;height:30px">
               <Row>
                   <i-col span="2"><span>编辑灰度发布</span></i-col>
                   <i-col span="2" offset="20"><Button type="primary" v-if="allow_gray_offline()" @click="btn_gray_release_offline">下线</Button></i-col>
               </Row>
            </p>
            <strong>版本信息</strong>
            <div style="line-height:40px;background-color:#f8f8f9">
                <Row>
                    <i-col span="12">
                        <Row>
                            <i-col span="10">新版：</i-col>
                            <i-col span="14">
                                <Button type="primary" size="small" style="margin-right:10px" v-if="allow_edit_rule()"  @click="btn_edit_gray_rule" >编辑策略</Button>
                                <Button type="primary" size="small" v-if="allow_new_take_over()"  @click="btn_switch_traffic('new')" >接管流量</Button>
                            </i-col>
                        </Row>
                    </i-col>
                    <i-col span="12">
                        <Row>
                            <i-col span="12">旧版：</i-col>
                            <i-col span="12"><Button  type="primary" size="small" v-if="allow_old_take_over()"   @click="btn_switch_traffic('old')" >接管流量</Button></i-col>
                        </Row>
                    </i-col>
                </Row>
            </div>
            <br>
            <strong>流量控制</strong>

            
            <div v-if="allow_show_gray_rule()">
                <p>将符合以下规则的流量引入灰度版本</p>
                <div  class="split" style="background-color:#f8f8f9;height:210px">
                    
                    <Split v-model="split1">
                        <div slot="left" class="left-split-pane" >
                            <Row>
                                <i-col span="6" offset="1">Cookie内容</i-col>
                                <i-col span=14 offset="3"> {{ gray_release_edit.match[0].headers.cookie.value}}</i-col>
                            </Row>

                            <Row>
                                <i-col span="6" offset="1">自定义Header</i-col>
                                <i-col span=14 offset="3">
                                    <Row>
                                        <i-col span="12">{{ gray_release_edit.match[0].headers.custom_header.key}} </i-col>
                                        <i-col span="12">{{ gray_release_edit.match[0].headers.custom_header.value}}</i-col>
                                    </Row>
                                </i-col>
                            </Row>
                            
                            <Row>
                                <i-col span="6" offset="1">操作系统</i-col>
                                <i-col span=14 offset="3"> {{ gray_release_edit.match[0].headers.user_agent.value}}</i-col>
                            </Row>
                            
                            <Row>
                                <i-col span="6" offset="1">URI</i-col>
                                <i-col span=14 offset="3"> {{ gray_release_edit.match[0].uri.value}}</i-col>
                            </Row>
                        </div>
                        <div slot="right" class="right-split-pane">
                            <p>流入:新版</p>
                        </div>
                    </Split>
                </div>
            </div>
            <div v-if="allow_recover()" class="gray_box2">
                <div v-if="allow_new_recover()" >
                    <span>流量全部流向:{{gray_release_edit.service}}新版</span>
                    <Button type='primary' style="margin-left:10px"   @click="btn_gray_recover" size="small">恢复</Button>
                </div>
                <div v-if="allow_old_recover()" >
                    <span>流量全部流向: {{gray_release_edit.service}}旧版</span>
                    <Button type='primary' style="margin-left:10px" @click="btn_gray_recover" size="small">恢复</Button>
                </div>
            </div>

            <div slot="footer" class="modal_footer">
                <Button type="primary"  @click="btn_close_gray_modal">关闭</Button>
            </div>
        </Modal>

        <!-- 编辑灰度策略 -->
        <Modal v-model="show_edit_gray_rule_modal"  id="gray_rule_modal"   title="编辑灰度策略" width="800"  :closable="false" @on-ok="submit_update_gray_rule">

            <Form ref="gray_release_edit" label-position="left"  :label-width="200" inline>
                <Form-Item label="Cookie">
                    <Select v-model="gray_release_edit.match[0].headers.cookie.type" style="width:150px" >
                        <template v-for="(key,val) in type_list1" >
                            <Option :key="key" :value="key" v-if="key === gray_release_edit.match[0].headers.cookie.type"  selected>{{ val }}</Option>
                            <Option :key="key" :value="key" v-else>{{ val }} </Option>
                        </template>
                    </Select>
                    <Input  v-model="gray_release_edit.match[0].headers.cookie.value" style="width:300px"   placeholder="key=value"/>
                </Form-Item>
                <Form-Item label="自定义header">
                    <Select v-model="gray_release_edit.match[0].headers.custom_header.type" style="width:150px" transfer>
                        <template v-for="(key,val) in type_list1" >
                            <Option :key="key" :value="key" v-if="key === gray_release_edit.match[0].headers.custom_header.type"  selected>{{ val }}</Option>
                            <Option :key="key" :value="key" v-else>{{ val }} </Option>
                        </template>
                    </Select>
                    <Input  v-model="gray_release_edit.match[0].headers.custom_header.key" style="width:200px"   placeholder="key"/>
                    <Input  v-model="gray_release_edit.match[0].headers.custom_header.value" style="width:200px"   placeholder="value"/>
                </Form-Item>
                <Form-Item label="URI">
                    <Select v-model="gray_release_edit.match[0].uri.type" style="width:150px"  transfer>
                        <template v-for="(key,val) in type_list2" >
                            <Option :key="key" :value="key" v-if="key === gray_release_edit.match[0].uri.type"  selected>{{ val }}</Option>
                            <Option :key="key" :value="key" v-else>{{ val }} </Option>
                        </template>
                    </Select>
                    <Input  v-model="gray_release_edit.match[0].uri.value" style="width:300px"   placeholder="URI"/>
                </Form-Item>
                <Form-Item label="流量来源于以下操作系统">
                    <CheckboxGroup v-model="gray_release_edit.match[0].headers.user_agent.value">
                            <template v-for="system in system_list" >
                                <Checkbox  :label="system" :key="system" :value="system" v-if="system in gray_release_edit.match[0].headers.user_agent.value" checked>{{system}}</Checkbox>
                                <Checkbox :label="system" :key="system" :value="system" v-else>{{system}}</Checkbox>
                            </template>
                    </CheckboxGroup>

                </Form-Item>
                <br>
            </Form>
        </Modal>
    </div>
</template>
<script>

import { public_list,update_release_v2,update_gray_release,offline_release_v2 } from  '@/api'
import { post } from '@/api/http'
import { show_simple_page,colors,get_placement } from '@/common/util' 
import { match_convert } from './public.js'
// 1、创建  2、发版成功（测试新版） 3、发版失败 4、灰度测试（金丝雀，灰度）  11、回滚成功 12、回滚失败 13、下线删除资源失败  99、发布完成
const Public_Create = 1
const Public_OK = 2  //新  蓝绿 灰度共用 代表全部流量指向新版本
const Public_Fail = 3  //旧 
const Public_Gray_Test = 4 //新旧 灰度测试当中
const Public_Gray_Fail = 5 //新旧灰度更新失败
const Public_Gray_OK = 6 //新旧 灰度更新成功
const Public_New_OK = 7
const Public_New_Fail = 8

const Public_Roll_OK = 11 // 旧 (灰度测试失败就需要回滚，回滚前两个版本的流量都有)
const Public_Roll_Fail = 12  //新 (新旧)
const Public_Offline_Fail = 13 //新
const Public_End = 99

// const Public_Status_Map = {
//     "Public_Fail": "创建发布失败",
//     "Public_Gray_Test":"发布灰度并测试",
//     "Public_Gray_Fail":"更新灰度失败",
//     "Public_Gray_OK":"更新灰度成功",
//     "Public_New_OK":"新版接管成功",
//     "Public_New_Fail":"新版接管失败",
//     "Public_Roll_OK":"回滚旧版成功",
//     "Public_Roll_Fail":"回滚旧版失败",
//     "Public_Offline_Fail":"下线失败",
//     "Public_End":"发布结束",
// }
const Public_Status_Map = {
    2: "发版成功",
    3: "创建发布失败",
    4:"发布灰度并测试",
    5:"更新灰度失败",
    6:"更新灰度成功",
    7:"新版接管成功",
    8:"新版接管失败",
    11:"回滚旧版成功",
    12:"回滚旧版失败",
    13:"下线失败",
    99:"发布结束",
}

export default {
    data() {
        return {
            format: [
                {
                    title: '项目',key: 'project'
                },
                {
                    title: '批次ID',key: 'id'
                },
                {
                    title: '服务',key: 'service_list',
                    render:(h,params)=>{
                        let service_list = params.row.service_list
                        let value=service_list
                        return h('span',value)
                    }
                },
                {
                    title: '发布类型',key: 'public_type',
                    render:(h,params)=>{
                        let release_type = params.row.public_type
                        let value=null
                        if(release_type==1){
                            value='蓝绿部署'
                        }else if (release_type==2){
                            value='灰度发布'
                        }else if (release_type==3){
                            value='滚动更新'
                        }
                        return h('span',value)
                    }
                },
                {
                    title: '发布状态',key: 'status',
                    render:(h,params)=>{
                        let release_status = params.row.status
                        let value = Public_Status_Map[release_status]
                        // console.log(value)
                        if(release_status==Public_Create){
                            return h('span',{
                                style: {
                                    color: colors['yellow'],
                                }
                            },value)
                        }else if (release_status == Public_Gray_Test) {
                            return h('span',{
                                style: {
                                    color: colors['gray'],
                                }
                            },value)

                        }else if ( [Public_Fail,Public_Roll_Fail,Public_Offline_Fail,Public_Gray_Fail,Public_New_Fail].includes(release_status) ){
                            return h('span',{
                                style: {
                                    color: colors['red'],
                                }
                            },value)
                        }else if ([Public_OK,Public_Roll_OK,Public_Gray_OK,Public_New_OK].includes(release_status)){             
                            return h('span',{
                                style: {
                                    color: colors['green'],
                                }
                            },value)
                        }else if (release_status==Public_End){
                            return h('span',{
                                style: {
                                    color: colors['black'],
                                }
                            },value)
                        }
                    }
                },

                {
                    title: '灰度路由匹配项',key: 'match',
                    render:(h,params)=>{
                        let match = params.row.match
                        // console.log(typeof match,JSON.stringify(match))
                        if(match==null || match==''){
                            return h('span','无')
                        }else{
                            let placement = get_placement(params)
                            let my_matcher = match_convert(match)
                            let value = JSON.stringify(my_matcher,undefined,4)
                            console.log(value)
                            return h('Poptip', {props:{'trigger':'hover','width':400,'word-wrap':true,'transfer':true,'placement':placement,content:value}},[
                                    h('a', '显示')
                            ]);
                        }
                    }
                },

                {
                    title: '创建时间',key: 'create_time'
                },
                {
                    title: '更新时间',key: 'update_time'
                },
                {
                    title: '操作',slot: 'action',width: 100,align: 'center'
                }
            ],
            split1:0.8,
            // 分页
            total_list: [],
            show_list: [],
            total: 0,
            pageSize: 10,

            show_edit_bg_modal: false,
            release_edit: {
                id: '',
                project: '',
                service_list: [],
                public_type: 1,
                // 后台的权重是单独存储，这里没必要使用service_details
                old_weight:'',
                new_weight:'',
                status: null,
            },

            show_edit_gray_modal:false,
            gray_release_edit:{
                project: '',
                service_list: [],
                public_type: 1,
                old_weight:'',
                new_weight:'',
                status: null,
                match: [
                    {
                        headers: {
                            user_agent: {
                                value:[],
                            },
                            cookie: {
                                type: "exact",
                                value: "",
                            },
                            custom_header: {
                                type: 'exact',
                                key: '',
                                value: '',
                            }
                        },
                        uri: {
                            type: 'prefix',
                            value: '',
                        }
                    }
                ],
            },
            type_list1:{
                '正则匹配':'regex',
                '完全匹配':'exact',
            },
            type_list2:{
                '前缀匹配':'prefix',
                '完全匹配':'exact',
            },
            system_list:['Windows','Linux','Mac OS','Android','IOS'],
            show_edit_gray_rule_modal: false,

        }
    },
    methods: {
        btn_close_gray_modal(){
            this.show_edit_gray_modal = false
        },

        //更新灰度策略
        submit_update_gray_rule() {
            let result = confirm("确定要更新灰度策略吗?")
            if(result == false) return 
            let data = this.gray_release_edit
            data['action'] = 'update_rule'
            if( data['service_list'].length==0){
                alert('服务不允许为空')
                return
            }
            post(update_gray_release,data).then(response=>{
                let info = JSON.stringify(response.data)
                if(info.indexOf('ok') != -1) {
                    this.$Message.success('更新成功')
                    this.gray_release_edit.status=Public_Gray_Test
                    this.refresh()
                }else {
                    alert("更新失败:"+info)
                }

            })
        }, 
        // 编辑灰度策略
        btn_edit_gray_rule(){
            this.show_edit_gray_rule_modal = true
        },
        allow_show_gray_rule(){
            if([4,5,6].includes(this.gray_release_edit.status)){
                return true
            }
            return false
        },
        allow_new_take_over(){
            if([4,6].includes(this.gray_release_edit.status)){
                return true
            }
            return false
        },      
        allow_old_take_over(){
            if([3,4,5,6,12].includes(this.gray_release_edit.status)){
                return true
            }
            return false 
        },
        //
        allow_edit_rule(){
            if([4,5,6].includes(this.gray_release_edit.status)){
                return true
            }
            return false 
        },
        allow_recover(){
            if([2,11].includes(this.gray_release_edit.status)){
                return true
            }
            return false    
        },
        allow_new_recover(){
            if([2].includes(this.gray_release_edit.status)){
                return true
            }
            return false    
        },
        allow_old_recover(){
            if([11].includes(this.gray_release_edit.status)){
                return true
            }
            return false    
        },
        // 灰度
        allow_gray_offline(){
            // 新版或者旧版接管流量
            if([2,11].includes(this.gray_release_edit.status)){
                return true
            }
            return false 
        },
        // 任务下线
        btn_gray_release_offline(){
            let data = this.gray_release_edit
            console.log(data)
            post(offline_release_v2,data).then(response=>{
                let info = JSON.stringify(response.data)
                if(info.indexOf('ok') != -1) {
                    this.$Message.success('下线成功')
                    this.show_edit_gray_modal = false
                    this.refresh()
                }else {
                    alert("下线失败:"+info)
                }
            })
        },

        btn_switch_traffic(target){
            let data = this.gray_release_edit
            if(target=='new'){
                data['new_weight']=100
                data['old_weight']=0
                data['action'] = 'new_take_over_traffic'
            }else{
                data['new_weight']=0
                data['old_weight']=100
                data['action'] = 'old_take_over_traffic'
            }
            post(update_gray_release,data).then(response=>{
                let info = JSON.stringify(response.data)
                if(info.indexOf('ok') != -1) {
                    this.$Message.success('接管流量成功')
                    this.refresh()
                    if(target=='new'){
                        this.gray_release_edit.status=Public_OK
                    }else{
                        this.gray_release_edit.status=Public_Roll_OK
                    }
                }else {
                    alert("更新失败:"+info)
                }
            })

        },

        btn_gray_recover(){
            let data = this.gray_release_edit
            data['action'] = 'recover_traffic'
            if( data['service_list'].length==0){
                alert('服务不允许为空')
                return
            }
            post(update_gray_release,data).then(response=>{
                let info = JSON.stringify(response.data)
                if(info.indexOf('ok') != -1) {
                    this.$Message.success('恢复成功')
                    this.gray_release_edit.status=Public_Gray_Test
                    this.refresh()
                }else {
                    alert("恢复失败:"+info)
                }

            })
        },
        changePage(index) {
            let _start = (index -1) * this.pageSize
            let _end = index * this.pageSize
            this.show_list = this.total_list.slice(_start,_end)
        },
        btn_close_bg_modal(){
            this.show_edit_bg_modal = false
        },
        // 任务下线
        btn_bg_release_offline(){
            let data = this.release_edit
            console.log('btn_bg_release_offline')
            post(offline_release_v2,data).then(response=>{
                let info = JSON.stringify(response.data)
                if(info.indexOf('ok') != -1) {
                    this.$Message.success('下线成功')
                    this.show_edit_bg_modal=false
                    this.refresh()
                }else {
                    alert("下线失败:"+info)
                }
            })
        },
        btn_change_weight(target){
            if(target=='new'){
                this.release_edit.new_weight=100
                this.release_edit.old_weight=0
            }else{
                this.release_edit.old_weight=100
                this.release_edit.new_weight=0
            }
            let data = this.release_edit
            console.log(data)
            post(update_release_v2,data).then(response=>{
                let info = JSON.stringify(response.data)
                if(info.indexOf('ok') != -1) {
                    this.$Message.success('更新成功')
                    this.refresh()
                    // 曾经的bug
                    if(target=='new'){
                        this.release_edit.status=Public_OK
                    }else{
                        this.release_edit.status=Public_Roll_OK
                    }
                }else {
                    alert("更新失败:"+info)
                }
            })
        },
        btn_edit_release(index){
            let release = this.show_list[index]
            if(release.public_type == 1){
                this.release_edit = release
                this.show_edit_bg_modal = true
            }else if(release.public_type == 2){
                this.gray_release_edit = release
                console.log(typeof this.gray_release_edit.match)
                this.show_edit_gray_modal = true
            }
        },
        refresh() {
            post(public_list).then(response =>{
                show_simple_page(this,response)
            })
        }
    },
    mounted: function() {
        setTimeout(() =>{
            this.refresh();
        },200); 
    }
}
</script>
<style scoped>
    .modal_footer {
        text-align:right;
        margin-bottom:5px;
        margin-top:5px
    }
    .traffic-split{
        height: 60px;
        line-height: 40px;
        border: 1px solid #dcdee2;
    }
    .split{
        height: 200px;
        line-height: 40px;
        border: 1px solid #dcdee2;
    }
    .split-pane{
        padding: 10px;
    }
    .left-split-pane{
        padding: 10px;
    }
    .right-split-pane{
        padding: 10px;
        line-height: 160px;
        text-align:center
    }
    #gray_rule_modal  .ivu-modal-wrap {
        z-index: 9999;
    }
    .gray_box2 {
        text-align:center;
        border:1px solid  #d7dde4;
        height:200px;
        line-height:200px;
    }
</style>